package dataserver.api;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.wenhao.jpa.Specifications;
import dataserver.mapper.SceneDeviceRelationRepository;
import dataserver.pojo.SceneDevice;
import dataserver.pojo.SceneDeviceRelation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class IesLabApi {

    @Value("${api.ieslab.url}")
    private String ieslabUrl;

    @Autowired
    private SceneDeviceRelationRepository sceneDeviceRelationRepository;

    /**
     * 获取积成在线检测数据-变压器光声光谱
     *
     * @param stationCode
     * @param equipmentId
     * @param url
     * @throws Exception
     */
    public IesLabResponseInfo getOnlineMonitorInfoTransForm(String stationCode, String equipmentId,String type, String url) {
        IesLabResponseInfo responseInfo = queryIesLabResponseInfo(stationCode, equipmentId, url);
        JSONArray jsonArray = setUnrealName1(stationCode, equipmentId, type,responseInfo.getData());
        responseInfo.setData(jsonArray);
        return responseInfo;
    }

    /**
     * 获取积成在线检测数据 铁芯电流 避雷器
     *
     * @param stationCode
     * @param equipmentId
     * @param url
     * @throws Exception
     */
    public IesLabResponseInfo getOnlineMonitorInfo(String stationCode, String equipmentId, String type,String url) {
        IesLabResponseInfo responseInfo = queryIesLabResponseInfo(stationCode, equipmentId, url);
        JSONArray jsonArray = setUnrealName2(stationCode, equipmentId, type, responseInfo.getData());
        responseInfo.setData(jsonArray);
        return responseInfo;
    }

    /**
     * 获取积成在线检测数据-特高频局放-变压器和电缆-密度微水
     *
     * @param stationCode
     * @param equipmentId
     * @param url
     * @throws Exception
     */
    public IesLabResponseInfo getOnlineMonitorInfo3(String stationCode, String equipmentId,String type, String url) {
        IesLabResponseInfo responseInfo = queryIesLabResponseInfo(stationCode, equipmentId, url);
        JSONArray jsonArray = setUnrealName3(stationCode, equipmentId, type,responseInfo.getData());
        responseInfo.setData(jsonArray);
        return responseInfo;
    }

    /**
     * 查询积成接口
     *
     * @param stationCode
     * @param equipmentId
     * @param type
     * @param url
     * @throws Exception
     */
    private IesLabResponseInfo queryIesLabResponseInfo(String stationCode, String equipmentId, String url){
        String result = HttpUtil.get(ieslabUrl + url + "?stationCode=" + stationCode + "&equipmentId=" + equipmentId);
        return JSONObject.parseObject(result, IesLabResponseInfo.class);
    }

    /**
     * 将结果添加 unrealName 字段 变压器光声光谱
     *
     * @param stationCode
     * @param equipmentId
     * @param jsonArray
     * @throws Exception
     */
    private JSONArray setUnrealName1(String stationCode, String equipmentId, String type, JSONArray jsonArray) {
        List<SceneDeviceRelation> targetData = getSceneDeviceRelation(stationCode, equipmentId, type);
        // 与模型关联数据绑定
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // 获取
            String eId = jsonObject.getString("transId");
            if (jsonObject.get("equipmentId") != null) {
                eId = jsonObject.getString("equipmentId");
            }
            String finalEId = eId;
            List<SceneDeviceRelation> eList = targetData.stream()
                    .filter(entity -> entity.getEquipmentId().equals(finalEId))
                    .collect(Collectors.toList());
            if (eList.size() > 0) {
                SceneDeviceRelation entity = eList.get(0);
                jsonObject.put("unrealName", entity.getUnrealName());
                if (entity.getSceneDevice() != null) {
                    SceneDevice sceneDevice = entity.getSceneDevice();
                    jsonObject.put("x", sceneDevice.getX());
                    jsonObject.put("y", sceneDevice.getY());
                    jsonObject.put("z", sceneDevice.getZ());
                }
            }
        }
        return jsonArray;
    }

    /**
     * 将结果添加 unrealName 字段  铁芯电流 避雷器
     *
     * @param stationCode
     * @param equipmentId
     * @param jsonArray
     * @throws Exception
     */
    private JSONArray setUnrealName2(String stationCode, String equipmentId, String type, JSONArray jsonArray) {
        // 设定新的返回数组
        JSONArray jsonArrayData = new JSONArray();
        List<SceneDeviceRelation> targetData = getSceneDeviceRelation(stationCode, equipmentId, type);
        for (int i = 0; i < targetData.size(); i++) {
            SceneDeviceRelation entity = targetData.get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("unrealName", entity.getUnrealName());
            jsonObject.put("transName", entity.getEquipmentName());
            jsonObject.put("transId", entity.getEquipmentId());
            String equipmentInfo = entity.getEquipmentInfo();
            if (entity.getSceneDevice() != null) {
                SceneDevice sceneDevice = entity.getSceneDevice();
                jsonObject.put("x", sceneDevice.getX());
                jsonObject.put("y", sceneDevice.getY());
                jsonObject.put("z", sceneDevice.getZ());
            }
            // 遍历积成数据
            for (int t = 0; t < jsonArray.size(); t++) {
                JSONObject jsonO = jsonArray.getJSONObject(t);
                // 获取
                String name = jsonO.getString("name");
                String value = "";
                if (jsonO.get("value") != null) {
                    value = jsonO.getString("value");
                } else if (jsonO.get("allCurrant") != null) {
                    value = jsonO.getString("allCurrant");
                }
                String[] names = name.split("\\.");
                String valueName = names[3] + "." + names[4];
                // 关联
                if (name.contains(equipmentInfo)) {
                    jsonObject.put(valueName, value);
                }
            }
            jsonArrayData.add(jsonObject);
        }
        return jsonArrayData;
    }


    /**
     * 将结果添加 unrealName 字段 -特高频局放-变压器和电缆-密度微水
     *
     * @param stationCode
     * @param equipmentId
     * @param jsonArray
     * @throws Exception
     */
    private JSONArray setUnrealName3(String stationCode, String equipmentId, String type, JSONArray jsonArray) {
        // 设定新的返回数组
        JSONArray jsonArrayData = new JSONArray();
        List<SceneDeviceRelation> targetData = getSceneDeviceRelation(stationCode, equipmentId, type);
        for (int i = 0; i < targetData.size(); i++) {
            SceneDeviceRelation entity = targetData.get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("unrealName", entity.getUnrealName());
            jsonObject.put("transName", entity.getEquipmentName());
            jsonObject.put("transId", entity.getEquipmentId());
            if (entity.getSceneDevice() != null) {
                SceneDevice sceneDevice = entity.getSceneDevice();
                jsonObject.put("x", sceneDevice.getX());
                jsonObject.put("y", sceneDevice.getY());
                jsonObject.put("z", sceneDevice.getZ());
            }
            String equipmentInfo = entity.getEquipmentInfo();
            if (StringUtils.isNotEmpty(equipmentInfo)) {
                // 遍历积成数据
                for (int t = 0; t < jsonArray.size(); t++) {
                    JSONObject jsonO = jsonArray.getJSONObject(t);
                    // 获取
                    String name = jsonO.getString("equipmentName");
                    // 关联
                    if (name.contains(equipmentInfo)) {
                        // 只选择其中一组数据
                        jsonObject.putAll(jsonO);
                        // 添加多组数据的方式
//                    // 获取点位的最后两位名称
//                    String[] names = name.split("\\.");
//                    String valueName = names[2]; //变压器和电缆
//                    if (names.length == 4) { //特高频局放-密度微水
//                        valueName = names[2] + "." + names[3];
//                    }
//                    // 将积成查询的属性和值传入到数据中
//                    jsonObject.put(valueName, jsonO);
                    }
                }
            }

            jsonArrayData.add(jsonObject);
        }
        return jsonArrayData;
    }

    /**
     * 获取该类型的关系信息
     *
     * @param stationCode
     * @param equipmentId
     * @throws Exception
     */
    private List<SceneDeviceRelation> getSceneDeviceRelation(String stationCode, String equipmentId, String type) {
        // 创建匹配器，需要查询条件请修改此处代码
        Specification<SceneDeviceRelation> specification = Specifications.<SceneDeviceRelation>and()
                .eq(!StringUtils.isBlank(stationCode), "stationId", stationCode)
                .eq(!StringUtils.isBlank(equipmentId), "equipmentId", equipmentId)
                .eq(!StringUtils.isBlank(type), "type", type)
//                .ne("equipmentId", null)
                .build();
        List<SceneDeviceRelation> targetData = sceneDeviceRelationRepository.findAll(specification);
        return targetData;
    }
}
